﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using Microsoft.SharePoint;

namespace Trig_AMJ_HR_Forms.Leave_Request_Dashboard
{
    public partial class Leave_Request_DashboardUserControl : UserControl
    {

        static DataTable dt = null;
        public static string SiteURL { get; set; }
        public static string MainLstName;

        public static string ClearanceLstName;
        public static string UnderLstName;
        public static string ExitLstName;
        public static string ResumptionLstName;

        public static string ClearanceMode;
        public static string ExitMode;
        public static string ResumpMode;
        public static string CancelMode;


        SPHelper obj = new SPHelper();
        ExceptionHandler err = new ExceptionHandler();
        bool handOverStatus = false;
        static bool ckLeaveStatus = false;
        string camlQry = null;
        static SPQuery qry;
        bool Users = false;
        SPListItem oItem = null;
        bool ckResStatus;




        public Leave_Request_DashboardUserControl()
        {
            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";
            MainLstName = "Leave Request Forms";
            ClearanceLstName = "Clearance Forms";
            //UnderLstName = "Undertaking Forms";
            ResumptionLstName = "Resumption of Duty Forms";
            ExitLstName = "HR Request Forms";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            lblError.Text = "";
            if (!IsPostBack)
            {
                try
                {
                    ckLeaveStatus = false;
                    dt = null;
                    Users = false;
                    SPSecurity.RunWithElevatedPrivileges(delegate() { GetLeaveRecords(); });
                }
                catch (Exception ex)
                {
                    err.GenerateExceptionLog("Leave_Request_Dashboard", ex.Message, "");
                }

            }

            if (dt != null && ckLeaveStatus == true)
            {
                gvLeaveDb.DataSource = dt;
                gvLeaveDb.DataBind();
            }

        }

        private void GetLeaveRecords()
        {
            dt = new DataTable();
            dt = CreateLeaveCols("SubmittedFor", "Reference_x0020_Number", "Cancel Leave Request", "ClearanceStatus", "HandoverStatus", "ExitStatus",
                "ResumptionStatus", "Print Leave");

            if (pplUsers.Entities.Count > 0)
                GetApprovedLeaves();
            else
                GetApprovedLeavesAll();
        }

        private DataTable CreateLeaveCols(params object[] cols)
        {
            foreach (string col in cols)
            {
                dt.Columns.Add(col);
            }
            return dt;
        }


        /// <summary>
        /// Get Approved leave records and bind in gridview
        /// </summary>
        private void GetApprovedLeaves()
        {
            string strstrUser = "";
            string[] strUsers = null;
            string fldUser = null;
            string[] fldUsers = null;
            if (Users)
            {
                strstrUser = pplUsers.CommaSeparatedAccounts;
                strUsers = strstrUser.Split(',');

                foreach (string user in strUsers)
                {
                    SPUser User = SPContext.Current.Web.SiteUsers[user];
                    SPFieldUserValue ofldUser = new SPFieldUserValue(SPContext.Current.Web, User.ID, User.Name);
                    fldUser = fldUser + ";" + ofldUser.User.Name;
                }
                fldUsers = fldUser.Split(';');
                strUsers = fldUsers;
            }

            else
            {
                strstrUser = SPContext.Current.Web.CurrentUser.Name;
                strUsers = strstrUser.Split(';');
            }

            //DataTable dt = new DataTable();
            DataTable dtSep;

            SPListItemCollection oItemColl = null;
            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPList oList = oWeb.Lists.TryGetList(MainLstName);
                    if (oList != null)
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        foreach (string user in strUsers)
                        {
                            if (!string.IsNullOrEmpty(user))
                            {
                                string userValue = user.Replace("//", "/");
                                string camlQry = "";
                                camlQry = "<Where><And><Eq><FieldRef Name=\"SubmittedFor\" /><Value Type=\"User\">" + userValue + "</Value></Eq><Eq>"
                                + "<FieldRef Name=\"Document_x0020_Status\" /><Value Type=\"Text\">Approved</Value></Eq></And></Where>";
                                oItemColl = obj.GetSPListItems(SiteURL, MainLstName, camlQry);
                                if (oItemColl.Count > 0)
                                {
                                    ckLeaveStatus = true;
                                    dtSep = new DataTable();
                                    dtSep = oItemColl.GetDataTable();
                                    dt.Merge(dtSep);
                                }
                                else
                                {
                                    DataRow dr = dt.NewRow();
                                    dr[0] = userValue;
                                    dr[1] = "No Records Found";
                                    dt.Rows.Add(dr);
                                }
                            }
                        }

                        oWeb.AllowUnsafeUpdates = false;
                    }
                    else
                    {
                        lblError.Text = "List not found"; lblError.ForeColor = System.Drawing.Color.Red;
                    }
                }
            }

            if (dt.Rows.Count > 0 && ckLeaveStatus == true)
            {
                gvLeaveDb.Visible = true;
                gvLeaveDb.DataSource = dt;
                gvLeaveDb.DataBind();
            }
            else
            {
                lblError.Text = "No records found"; lblError.ForeColor = System.Drawing.Color.Green;
                gvLeaveDb.DataSource = null;
                gvLeaveDb.DataBind();
                gvLeaveDb.Visible = false;
            }
        }


        private void GetApprovedLeavesAll()
        {
            DataTable dtSep;
            SPListItemCollection oItemColl = null;
            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPList oList = oWeb.Lists.TryGetList(MainLstName);
                    if (oList != null)
                    {
                        oWeb.AllowUnsafeUpdates = true;

                        camlQry = "<Where><Eq><FieldRef Name=\"Document_x0020_Status\" /><Value Type=\"Text\">Approved</Value></Eq></Where>";
                        oItemColl = obj.GetSPListItems(SiteURL, MainLstName, camlQry);
                        if (oItemColl.Count > 0)
                        {
                            ckLeaveStatus = true;
                            dtSep = new DataTable();
                            dtSep = oItemColl.GetDataTable();
                            dt.Merge(dtSep);
                        }
                        else
                        {
                            lblError.Text = "Records not found"; lblError.ForeColor = System.Drawing.Color.Red;
                        }


                        oWeb.AllowUnsafeUpdates = false;
                    }
                    else
                    {
                        lblError.Text = "List not found"; lblError.ForeColor = System.Drawing.Color.Red;
                    }
                }
            }

            if (dt.Rows.Count > 0 && ckLeaveStatus == true)
            {
                gvLeaveDb.Visible = true;
                gvLeaveDb.DataSource = dt;
                gvLeaveDb.DataBind();
            }
            else
            {
                lblError.Text = "No records found"; lblError.ForeColor = System.Drawing.Color.Green;
                gvLeaveDb.DataSource = null;
                gvLeaveDb.DataBind();
                gvLeaveDb.Visible = false;
            }
        }


        protected void gvLeaveDb_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                object rowIndexValue = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[1];
                object rowIndexUser = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[0];



                if (!rowIndexValue.ToString().Contains("Records"))
                {
                    #region "Find Controls"

                    Label refID = e.Row.FindControl("lblRefNo") as Label;

                    //Label LeaveUser = e.Row.FindControl("lblSumittedUser") as Label;

                    HiddenField hdnClearance = e.Row.FindControl("hdnClearance") as HiddenField;
                    HiddenField hdnUnder = e.Row.FindControl("hdnUnder") as HiddenField;
                    HiddenField hdnResumption = e.Row.FindControl("hdnResumption") as HiddenField;
                    HiddenField hdnExit = e.Row.FindControl("hdnExit") as HiddenField;

                    HyperLink lnkClearance = e.Row.FindControl("lnkClearance") as HyperLink;
                    LinkButton lnkUndertaking = e.Row.FindControl("lnkUndertaking") as LinkButton;
                    HyperLink lnkExitPermit = e.Row.FindControl("lnkExitPermit") as HyperLink;
                    HyperLink lnkResumpDuty = e.Row.FindControl("lnkResumpDuty") as HyperLink;
                    HyperLink lnkPrintLeave = e.Row.FindControl("lnkPrintLeave") as HyperLink;

                    #endregion

                    if (hdnUnder.Value == "Yes")
                        lnkUndertaking.Text = "View";

                    ClearanceMode = CheckStatusCell(hdnClearance, lnkClearance, refID.Text, ClearanceLstName);
                    ExitMode = CheckStatusCell(hdnExit, lnkExitPermit, refID.Text, ExitLstName);
                    ResumpMode = CheckStatusCell(hdnResumption, lnkResumpDuty, refID.Text, ResumptionLstName);

                    string clearanceURL = SPContext.Current.Site.Url + "/_Layouts/Trig_AMJ_HR_Forms/Clearance_Action_Form.aspx?LeaveRefID=" + refID.Text + "&Mode=" + ClearanceMode;
                    string undertakingURL = SPContext.Current.Site.Url + "/_Layouts/Trig_AMJ_HR_Forms/Undertaking_Form.aspx?RefID=" + refID.Text;
                    string exitURL = SPContext.Current.Site.Url + "/_Layouts/Trig_AMJ_HR_Forms/HRRequest_Form.aspx?LeaveRefID=" + refID.Text + "&Mode=" + ExitMode;
                    string resumptionURL = SPContext.Current.Site.Url + "/_Layouts/Trig_AMJ_HR_Forms/Resumption_Duty_Form.aspx?LeaveRefID=" + refID.Text + "&Mode=" + ResumpMode;
                    string printURL = SPContext.Current.Site.Url + "/_Layouts/Trig_AMJ_HR_Forms/Leave_Request_Print.aspx?Mode=Print&RefID=" + refID.Text;

                    if (!string.IsNullOrEmpty(refID.Text))
                    {
                        //lnkClearance.Attributes.Add("onclick", "javascript:return OpenDialogbox('" + clearanceURL + "','" + 500 + "','" + 625 + "')");
                        //lnkUndertaking.Attributes.Add("onclick", "javascript:return OpenDialogbox('" + undertakingURL + "','" + 500 + "','" + 625 + "')");
                        //lnkExitPermit.Attributes.Add("onclick", "javascript:return OpenDialogbox('" + exitURL + "','" + 1000 + "','" + 1100 + "')");
                        //lnkResumpDuty.Attributes.Add("onclick", "javascript:return OpenDialogbox('" + resumptionURL + "','" + 1000 + "','" + 900 + "')");
                        //lnkPrintLeave.Attributes.Add("onclick", "javascript:return OpenDialogbox('" + printURL + "','" + 500 + "','" + 1000 + "')");

                        lnkClearance.NavigateUrl = clearanceURL;
                        lnkExitPermit.NavigateUrl = exitURL;
                        lnkResumpDuty.NavigateUrl = resumptionURL;
                        lnkPrintLeave.NavigateUrl = printURL;
                        //lnkUndertaking.NavigateUrl = undertakingURL;
                        lnkUndertaking.Attributes.Add("onclick", "javascript:return OpenDialogbox('" + undertakingURL + "','" + 500 + "','" + 1050 + "')");


                    }

                }
                else
                {
                    RecordsNotFound(e, rowIndexUser, rowIndexValue);
                }

            }

        }


        protected void RecordsNotFound(GridViewRowEventArgs e, object rowIndexUser, object rowIndexValue)
        {
            int celssCnt = e.Row.Cells.Count;
            for (int i = 0; i < celssCnt; i++)
            {
                e.Row.Cells[0].Text = rowIndexUser.ToString();
                e.Row.Cells[1].Text = rowIndexValue.ToString();
                e.Row.Cells[1].ColumnSpan = 7;
                e.Row.Cells[1].ForeColor = System.Drawing.Color.Red;
                e.Row.Cells[1].Style.Add("text-align", "left");
                if (i > 1)
                    e.Row.Cells[i].Visible = false;
            }
        }


        private string CheckStatusCell(HiddenField hdnValue, HyperLink lnkBtn, string refID, string corresSrsLstName)
        {

            string mode = null;
            if (hdnValue.Value == "Yes")
            {
                lnkBtn.Text = "View";
                mode = "View";

            }
            else
            {
                // To Check the form submitted the new entry in Resumption Form
                if (CheckEntryForm(refID, corresSrsLstName))
                {
                    lnkBtn.Text = "View";
                    mode = "View";
                }
                else
                {
                    lnkBtn.Text = "Generate";
                    mode = "New";
                }
            }

            return mode;
        }


        private bool CheckEntryForm(string refID, string corresSrsLstName)
        {
            try
            {
                qry = new SPQuery();
                camlQry = "<Where><Eq><FieldRef Name=\"LeaveReferenceNo\" /><Value Type=\"Text\">" + refID + "</Value></Eq></Where>";
                qry.Query = camlQry;
                qry.ViewFields = "<FieldRef Name='LeaveReferenceNo' />";
                oItem = obj.GetSPListItem(SiteURL, corresSrsLstName, qry);
                if (oItem != null)
                    ckResStatus = true;
                else
                    ckResStatus = false;

            }
            catch (Exception ex)
            {
                err.GenerateExceptionLog("Leave_Request_DashboardUserControl : ", ex.Message, "CheckResumption");
            }
            return ckResStatus;
        }

        protected void btnGetLeaveRec_Click(object sender, EventArgs e)
        {
            try
            {
                Users = true;
                SPSecurity.RunWithElevatedPrivileges(delegate() { GetLeaveRecords(); });
            }
            catch (Exception ex)
            {
                err.GenerateExceptionLog("Trig_AMJ_HR_Forms : Leave_Request_DashboardUserControl :", ex.Message, "btnGetLeaveRec");
            }

        }


        protected void btnClear_Click(object sender, EventArgs e)
        {
            try
            {
                pplUsers.Entities.Clear();
                gvLeaveDb.DataSource = null;
                gvLeaveDb.DataBind();
                gvLeaveDb.Visible = false;

            }
            catch (Exception ex)
            {
                err.GenerateExceptionLog("Trig_AMJ_HR_Forms : Leave_Request_DashboardUserControl :", ex.Message, "btnClear_Click");
            }

        }
    }
}
